package com.css.bjdt_core.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ExecutorPool {

	private static ExecutorService pool;

	private static ExecutorService cachePool;

	private static ExecutorService validationCachePool;

	private static Log logger = LogFactory.getLog(ExecutorPool.class);

	/*public static ExecutorService getPool() {
		if (null == pool) {
			pool = java.util.concurrent.Executors.newFixedThreadPool(300);
		}
		return pool;
	}*/

	private ExecutorPool() {
		//		pool = java.util.concurrent.Executors.newFixedThreadPool(200);
		pool = new ThreadPoolExecutor(200, 250, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		cachePool = Executors.newSingleThreadExecutor();
		validationCachePool = Executors.newSingleThreadExecutor();
	}

	private static ExecutorPool executors;

	public static ExecutorPool getInstance() {
		//int cpuNum = Runtime.getRuntime().availableProcessors();
		if (executors == null) {
			executors = new ExecutorPool();
		}
		return executors;
	}

	public ExecutorService getPool() {
		return pool;
	}

	public ExecutorService getCachePool() {
		return cachePool;
	}

	public ExecutorService getValidationCachePool() {
		return validationCachePool;
	}

	public void shutdownAndAwaitTermination() {
		pool.shutdown();
		cachePool.shutdown();
		validationCachePool.shutdown();
		try {
			pool.awaitTermination(30, TimeUnit.MINUTES);
			cachePool.awaitTermination(30, TimeUnit.MINUTES);
			validationCachePool.awaitTermination(30, TimeUnit.MINUTES);
		} catch (InterruptedException e) {
			logger.error(e);
		} finally {
			pool = null;
			cachePool = null;
			validationCachePool = null;
		}
	}
}
